<template>
  <div>
    <div style="padding:15px 0 10px">
      <el-button class="addRow" type="primary" round size="mini" @click="add">新增一行</el-button>
      <el-button class="delRow" type="danger" round size="mini" @click="delArr">删除</el-button>
    </div>
    <el-table
    ref="cutRef"
    :data="dataList"
    tooltip-effect="dark"
    style="width: 100%"
    @selection-change="typeHandleSelectionChange"
    border>
    <el-table-column
      type="selection"
      width="55">
    </el-table-column>
    <el-table-column
    type="index"
      label="序号"
      width="100">
    </el-table-column>
    <el-table-column
      v-for="(item,index) in tableNameList"
      :key="index"
      :prop="item.prop"
      :label="item.label"
      width="150">
      <template slot-scope="scope">
        <el-input size="small" v-model="scope.row[item.prop]" v-show="scope.row.id == clickId" ></el-input>
        <span v-show="scope.row.id !== clickId">{{scope.row[item.prop]}}</span>
      </template>
    </el-table-column>
    <el-table-column label="操作">
      <template slot-scope="scope">
        <div v-if="scope.row.id !== clickId">
          <el-button
            size="mini"
            @click="handleEdit(scope.row)">编辑</el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)">删除</el-button>
        </div>
        <div v-else>
          <el-button
            size="mini"
            type="success"
            @click="handleSave(scope.row)">保存</el-button>
          <el-button
            size="mini"
            type="warning"
            @click="handleCancel(scope.row)">取消</el-button>
        </div>
      </template>
    </el-table-column>
    </el-table>
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page.sync="page"
      :page-sizes="[5, 10, 20, 40]"
      :page-size="100"
      layout="sizes, prev, pager, next"
      :total="1000">
    </el-pagination>
  </div>
</template>

<script>
import Qs from 'qs'
export default {
  name:'TableTemplate',
  data(){
    return{
      //数据列表
      dataList:[],
      //表格名字列表
      tableNameList:[],
      oldValue:null,
      //nav选择的值
      flag:null,
      //url前缀
      befUrl:'/stoneType/',
      //批量删除的数组
      delArray:null,
      isDel:true,
      clickId:null,
      page:1,
      limit:5
    }
  },
  created(){ 
    //父组件的flag值
    this.$bus.$on('stone_flag',(val) => {
      this.flag = val
      this.$store.commit('setCategoryIndex',1)
      //进入石料基础设置时
      if(val == 1){
        this.tableNameList = [
          {label:'石料编码',prop:'code'},
          {label:'石料名称',prop:'name'},
          {label:'单位',prop:'company'},
        ];
        this.befUrl = '/stoneType/'
      }
      //进入商品资料基础设置时
      if(val == 2){
        this.tableNameList = [
            {label:'成色编码',prop:'csEncoding'},
            {label:'成色名称',prop:'csName'},
            {label:'重量单位',prop:'weight'},
            {label:'成分比例',prop:'proportion'},
            {label:'成色类别',prop:'sort'},
            {label:'千足料名称',prop:'qianzuliaoName'},
          ];
        this.befUrl = '/csSet/'
      }
      this.getList()
    })
    this.getList();
  },
  methods:{
    //封装http
    http(url,params){
      return new Promise((resolve,reject) => {
        this.$http({
          url,
          method:'post',
          params
        })
        .then(res => {
          resolve(res.data)
        })
        .catch(err => {
          reject(err)
        })
      })
    },
    // 获取列表
    getList(){
      console.log('发送http');
      // this.http(this.befUrl + 'selectByPage',{page:this.page,limit:this.limit})
      this.http(this.befUrl + 'selectByPage',{limit:this.limit,page:this.page})
      .then(res => {
        console.log(res.data);
        console.log(this.befUrl);
        this.dataList = res.data
      })
      .catch(err => {
        console.log(err);
      })    
    },
    //编辑
    handleEdit(row){
      this.oldValue = Object.assign({},row)
      console.log(row);
      this.clickId = row.id
    },
    //保存
    handleSave(row){
      console.log(row);
      let nameObj = {}
      this.tableNameList.forEach((item) =>{
        nameObj[item.prop] = row[item.prop]
      })
      if(Object.keys(row).length > 1 || row.id){
      this.http(this.befUrl + 'update',nameObj)
      .then((res) => {
        console.log(res);
        console.log(row);
        if(res.code == 200){
            this.$message({
            message:'保存成功',
            type:'success'
          })
          this.getList()
          this.clickId = ''
        }else{
          this.$message.error('保存失败')
        }
      })
      .catch(err => {
        this.$message.error('保存失败')
        console.log(err);
      })
      }else{
        this.$message.error('输入内容不能为空,保存失败')
      }
      
    },
    //取消修改
    handleCancel(row){
      // console.log(this.oldValue);
      // console.log(this.dataList);
      if(this.isDel){
          this.dataList.forEach((item,index) => {
          if(item.id == row.id){
            this.$set(this.dataList,index,this.oldValue)
          }
        })
      }else{
          this.dataList = this.dataList.filter(item => {
          return item.id > 0
        })
      }
      this.isDel = true
      console.log(this.dataList);
      this.clickId = null
    },
    //删除
    handleDelete(row){
      console.log(row.id);
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          this.http(this.befUrl + 'delete',{
            id: row.id
          })
          .then(res => {
            if(res.code !== '200'){
              this.$message.error('删除失败')
              console.log(res.code);
              return
            }
            this.$message({
              message:'删除成功',
              type:'success'
            })
            this.getList()
            console.log(res);
          })
          .catch(err => {
            console.log(err);
            this.$message.error('删除失败')
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });          
        });
    },
    // 新增
    add(){
      this.dataList.push({id:null})
      this.isDel = false
    },
    //多选事件
    typeHandleSelectionChange(val){
      this.delArray = val.map(item => {
        return item.id
      })
      console.log(this.delArray);
    },
    //批量删除
    //Qs.stringify({arr},{arrayFormat:'repeat'})
    delArr(){
      let arr = this.delArray
      if(!this.delArray[0]){
        return 
      }
      this.$confirm('此操作将永久删除该数据, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          this.$http({
            url:this.befUrl + 'deleteBatch' + '?' + Qs.stringify({idArr:arr},{arrayFormat:'repeat'}),
            method:'post', 
          })
          .then(res => {
            console.log(res.data.code != 200,res.data);
            if(res.data.code != 200) {
              console.log(res);
              return this.$message.error('删除失败')
            }
            this.$message({
              type:'success',
              message:'删除成功'
            })
            this.getList()
            console.log(res);
          })
          .catch(err => {
            this.$message.error('删除失败')
            console.log(err);
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });     
        })
    },
    //分页
    handleSizeChange(val){
      this.limit = val
      this.getList()
    },
    handleCurrentChange(val){
      this.page = val
      this.getList()
    },
  },
  computed:{
    //取出categoryIndex值
    categoryIndex: function(){
      return this.$store.state.categoryIndex
    } 
  },
  watch:{
    // 动态添加请求参数
    categoryIndex(newVal){
      console.log('分类值'+newVal);
      if(this.flag == 1){
        switch (newVal) {
        //种类
        case 1:
          this.befUrl = '/stoneType/';
          // this.tableNameList = ['石料编码','石料名称','单位'];
          this.tableNameList = [
          {label:'石料编码',prop:'code'},
          {label:'石料名称',prop:'name'},
          {label:'单位',prop:'company'},
        ]
          break;
        //颜色
        case 2:
          this.befUrl = '/stoneColor/';
          this.tableNameList = [
            {label:'石料颜色',prop:'color'},
            {label:'参数',prop:'param'},
            {label:'价格系数',prop:'priceFactor'},
          ]
          break;
        //净度
        case 3:
          this.befUrl = '/stoneClean/';
          this.tableNameList = [
            {label:'石料净度',prop:'code'},
            {label:'价格系数',prop:'company'},
          ]
          break;
        //切工
        case 4:
          this.befUrl = '/stoneCut/';
          this.tableNameList = [
            {label:'石料切工',prop:'color'},
            {label:'切工说明',prop:'param'},
          ];
          break;
        //火彩
        case 5:
          this.befUrl = '/firecolor/';
          this.tableNameList = [
            {label:'石料火彩',prop:'color'},
            {label:'火彩说明',prop:'param'},
          ];
          break;
        //形状
        case 6:
          this.befUrl = '/stoneShape/';
          this.tableNameList = [
            {label:'石料形状',prop:'shape'},
            {label:'形状说明',prop:'instructions'},
          ];
          break;
        //规格
        case 7:
          this.befUrl = '/specs/';
          this.tableNameList = [
            {label:'石料规格',prop:'specs'},
            {label:'形状说明',prop:'instructions'},
          ];
          break;
        //质地
        case 8:
          this.befUrl = '/texture/';
          this.tableNameList = [
            {label:'石料质地',prop:'texture'},
            {label:'形状说明',prop:'instructions'},
          ];
          break;
        //水头
        case 9:
          this.befUrl = '/waterhead/';
          this.tableNameList = [
            {label:'水头',prop:'waterhead'},
            {label:'形状说明',prop:'instructions'},
          ];
          break;
        }
      }
      if(this.flag == 2){
        switch (newVal) {
        //成色设置
        case 1:
          this.befUrl = '/csSet/';
          this.tableNameList = [
            {label:'成色编码',prop:'csEncoding'},
            {label:'成色名称',prop:'csName'},
            {label:'重量单位',prop:'weight'},
            {label:'成分比例',prop:'proportion'},
            {label:'成色类别',prop:'sort'},
            {label:'千足料名称',prop:'qianzuliaoName'},
          ];
          break;
        //属性设置
        case 2:
          this.befUrl = '/propertySet/';
          this.tableNameList = [
            {label:'属性编码',prop:'propertyEncoding'},
            {label:'属性名称',prop:'propertyName'},
          ];
          break;
        //款式分类设置
        case 3:
          this.tableNameList = ['款式分类编码','款式分类名称'];
          this.tableNameList = [
            {label:'款式分类编码',prop:'styleEncoding'},
            {label:'款式分类名称',prop:'styleName'},
          ];
          break;
        //商品类型设置
        case 4:
          this.befUrl = '/typeSet/';
          this.tableNameList = [
            {label:'类型编码',prop:'styleEncoding'},
            {label:'类型名称',prop:'styleName'},
            {label:'分配录入模板',prop:'styleName'},
          ];
          break;
        //含金量设置
        case 5:
          this.befUrl = '/goldContentSet/';
          this.tableNameList = [
            {label:'含金量',prop:'goldContent'},
            {label:'含金量名称',prop:'goldContentName'},
          ];
          break;
        //回收旧料名称设置
        case 6:
          this.befUrl = '/oldMaterialSet/';
          this.tableNameList = [
            {label:'旧料编码',prop:'"oldmaterialEncoding'},
            {label:'旧料名称',prop:'oldmaterialName'},
            {label:'料价',prop:'price'},
          ];
          break;
        //价格类型设置
        case 7:
          this.befUrl = '/jglxSet/';
          this.tableNameList = [
            {label:'价格编码',prop:'"oldmaterialEncoding'},
            {label:'价格类型',prop:'oldmaterialName'},
            {label:'打折标志',prop:'price'},
          ];
          break;
        //重量单位设置
        case 8:
          this.befUrl = '/zldwSet/';
          this.tableNameList = ['重量编码','重量名称'];
          break;
        //商品分类设置
        case 9:
          this.befUrl = '/spflSet/';
          this.tableNameList = ['一级分类','二级分类','分类别名','分类系数'];
          break;
        //商品系列设置
        case 10:
          this.befUrl = '/spxlSet/';
          this.tableNameList = ['系列名称','系列说明'];
          break;
        //提成分类设置
        case 11:
          this.befUrl = '/tcSet/';
          this.tableNameList = ['提成分类名称','提成分类说明'];
          break;
        //币别设置
        case 12:
          this.befUrl = '/bbSet/';
          this.tableNameList = ['币别编码','币别名称','汇率','本位币'];
          break;
        }
      }
      this.getList()
    }
  }
}
</script>

<style>

</style>